package com.campusmarket.controller;

import com.campusmarket.common.base.BaseController;
import com.campusmarket.dto.LayuiDataGridResult;
import com.campusmarket.dto.LayuiResult;
import com.campusmarket.model.Coin_order;
import com.campusmarket.model.Commodity;
import com.campusmarket.model.User;
import com.campusmarket.service.Coin_orderService;
import com.campusmarket.service.CommodityService;
import com.campusmarket.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;


import javax.servlet.http.HttpSession;

@Controller
@RequestMapping("/user")
public class UserController extends BaseController{

    @Autowired
    private UserService userService;

    @Autowired
    private Coin_orderService coin_orderService;

    @Autowired
    private CommodityService commodityService;

    @RequestMapping("/register")
    public String register(User user,HttpSession session){
        boolean flag=userService.register(user);
        if(flag==true){
            log.info("注册成功!");
            //如果注册成功,将登陆信息放到session中
            session.setAttribute("currentUser",user);
            //跳转到XX界面
            return "interface/user";
        }else{
            log.info("注册失败!");
            return "interface/login";
        }
    }

    @RequestMapping("/login")
    public String login(String username,String password,HttpSession session){
        User user=userService.selectByAccount(username);
        if(user!=null&&user.getPassword().equals(password)){
            log.info("登陆成功!");
            session.setAttribute("currentUser",user);
            //跳转到用户主页
            if(username.equals("admin")) return "interface/administrator";
            else return "interface/user";
        }else {
            log.info("登陆失败!");
            return "interface/login";
        }
    }

    @RequestMapping("/user_edit")
    public String user_edit(User user) throws Exception {
        boolean flag=userService.user_edit(user);
        if(flag==true){
            log.info("修改成功!");
            //新数据放到数据库中，刷新当前界面
            userService.update(user);

            return "interface/user_edit";
        }else {
            log.info("修改失败!");
            return "interface/user_edit";
        }
    }

    @RequestMapping("/add_user")
    public String add_user(User user) throws Exception {
        User flag=userService.insert(user);
        if(flag!=null){
            log.info("添加成功!");

            //跳转界面
            if(user.getUserName().equals("admin")) return "interface/adminstrator";

            else return "interface/user";
        }else {
            log.info("添加失败!");
            return "interface/add_user";
        }
    }




    @RequestMapping(value = "/del_user",produces = "application/json;charset=utf-8",method = RequestMethod.POST)
    @ResponseBody
    public LayuiResult del_user(Long id) throws Exception {
        LayuiResult result=new LayuiResult();
        try{
            userService.delete(id);
            result.setStatus(LayuiResult.OK);
            result.setMsg("删除成功!");
        }catch(Exception e){
            result.setStatus(LayuiResult.FAIL);
            result.setMsg("删除用户时发生异常!");
        }
        return result;
    }

    @RequestMapping(value="/list.json",produces = "application/json;charset=utf-8",method = RequestMethod.POST)
    @ResponseBody
    public LayuiDataGridResult list(int limit, int page, String key, HttpSession session) throws Exception{
        LayuiDataGridResult result=userService.selectListByPage(page,limit,key,null);
        return result;
    }

    /**
     * 处理更新的请求
     * @param model
     * @return
     * @throws Exception
     */
    @RequestMapping(value={"/add", "/edit"})
    public String form(User user, HttpSession session,Model model) throws Exception{
        if(user.getId()!=null&&user.getId()>0){
            userService.update(user);
            User u=(User)session.getAttribute("currentUser");
            if(u.getId().equals(user.getId())){
                session.setAttribute("currentUser",user);
            }
        }else{
            userService.insert(user);
        };
        User currentUser=(User)session.getAttribute("currentUser");
        //admin账号默认为管理员
        if(currentUser!=null&&currentUser.getUserName().equals("admin")){
            return "interface/admin_operation_user";
        }else{
            return "interface/user";
        }
    }


    @RequestMapping("/chongzhi")
    public String chongqian(Coin_order order,HttpSession session) throws Exception {
        User user=(User)session.getAttribute("currentUser");
        if(user!=null){
            order.setUserId(user.getId());
        }
        //插入充值记录
        coin_orderService.insert(order);
        //更改用户coin
        if(user.getCoin()==null){
            user.setCoin(0F);
        }
        user.setCoin(user.getCoin()+order.getChCoin());
        userService.update(user);
        return "interface/user";
    }

    @RequestMapping(value = "/buy",produces = "application/json;charset=utf-8")
    @ResponseBody
    public LayuiResult buy(Long id,HttpSession session) throws Exception {
        LayuiResult result=new LayuiResult();
        try{
            Commodity commodity=commodityService.queryById(id);
            commodity.setBuy(true);
            commodityService.update(commodity);
            User user=(User)session.getAttribute("currentUser");
            user.setCoin(user.getCoin()-commodity.getComPrice());
            result.setStatus(LayuiResult.OK);
            result.setMsg("购买成功!");
        }catch(Exception e){
            result.setStatus(LayuiResult.FAIL);
            result.setMsg("删除用户时发生异常!");
        }
        return result;
    }

}
